<template>
  <view class="container">
    <!-- 标签页 -->
    <scroll-view 
      class="tab-scroll" 
      scroll-x 
      :scroll-left="scrollLeft"
      scroll-with-animation
    >
      <view class="tab-container">
        <view 
          class="tab-item" 
          :class="{ active: activeTab === index }"
          v-for="(tab, index) in tabs" 
          :key="index"
          @click="switchTab(index)"
        >
          {{ tab.name }}
        </view>
      </view>
    </scroll-view>

    <!-- 订单列表 -->
    <view class="orders-container">
      <view v-if="loading" class="loading">加载中...</view>
      
      <view v-else-if="currentOrders.length === 0" class="empty">
        暂无订单
      </view>
      
      <view 
        v-else 
        class="order-card" 
        v-for="(order, index) in currentOrders" 
        :key="index"
        @click="goToOrderDetail(order)"
      >
        <view class="order-header">
          <text class="order-no">订单编号：{{ order.code }}</text>
          <text class="order-status">{{ order.status_title }}</text>
        </view>
        
        <view class="order-body">
          <image :src="order.img" mode="aspectFill"></image>
          <view class="order-info">
            <view class="info-row">
              <text class="product-title">{{ order.title }}</text>
              <text class="price">¥{{ order.price }}</text>
            </view>
            <view class="info-row">
              <text class="product-spec">{{ order.norm }}</text>
              <text class="count">x{{ order.num }}</text>
            </view>
            <view class="info-row">
              <text class="order-time">下单时间：{{ order.createtime }}</text>
            </view>
          </view>
        </view>
        
        <view class="order-footer">
          <view class="order-actions">
              <button 
                v-if="canDelete(order.status)" 
                class="action-btn delete-btn" 
                @click.stop="deleteOrder(order.id)"
              >
                删除订单
              </button>
              <button 
              v-if="canRefund(order.status)" 
              class="action-btn" 
              @click.stop="applyRefund(order.id)"
              style="border: #6E6E6E 1px solid;color: #6E6E6E;"
              >
              退款/售后
            </button>
            <button style="border: #FF8000 solid 1px;color: #FF8000;" class="action-btn" @click.stop="buyAgain(order.goods_id)">再次购买</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { orderApi } from '@/api/indexAPI.js';

export default {
  data() {
    return {
      activeTab: 0,
      scrollLeft: 0,
      tabs: [
        { name: '全部', status: null }
      ],
      orders: [],
      loading: true,
      userId: ''
    };
  },
  
  computed: {
    currentOrders() {
      // 当前标签下的订单列表
      return this.orders;
    }
  },
  
  onLoad(options) {
    // 获取用户ID
    this.userId = uni.getStorageSync('userId') || '';
    
    // 获取标签页数据
    this.getOrderTabs(options);
  },
  
  methods: {
    // 获取订单标签页
    getOrderTabs(options) {
      this.loading = true;
      
      // 发起请求获取标签页数据
      orderApi.getOrderList({
        user_id: this.userId
      }).then(res => {
        // 始终确保"全部"标签在第一位
        let tabs = [{ name: '全部', status: null }];
        
        if (res && res.data && res.data.tabs) {
          // 处理远程标签页数据，过滤掉可能重复的"全部"标签
          const remoteTabs = res.data.tabs
            .filter(tab => tab.name !== '全部') // 过滤掉远程数据中的"全部"标签
            .map(tab => ({
              name: tab.name,
              status: tab.status
            }));
          
          // 合并标签页
          tabs = [...tabs, ...remoteTabs];
        }
        
        // 更新标签页数据
        this.tabs = tabs;
        
        // 检查是否有从个人中心传来的状态参数
        if (options && options.status !== undefined) {
          // 根据传入的状态值找到对应的标签索引
          const statusIndex = this.tabs.findIndex(tab => tab.status == options.status);
          if (statusIndex !== -1) {
            // 设置活动标签页
            this.activeTab = statusIndex;
          }
        }
        
        // 获取订单列表
        this.getOrderList();
      }).catch(err => {
        console.error('获取订单标签失败:', err);
        // 出错时使用默认的"全部"标签并获取订单列表
        this.tabs = [{ name: '全部', status: null }];
        this.getOrderList();
      });
    },
    
    // 判断是否可以申请退款
    canRefund(status) {
      // 待支付(1)、已退款(7)、已取消(8)不能申请退款
      const nonRefundableStatus = [1, 7, 8];
      return !nonRefundableStatus.includes(status);
    },
    
    // 判断是否可以删除订单
    canDelete(status) {
      // 已收货(4)、已评价(5)、已退款(7)、已取消(8)可以删除订单
      const deletableStatus = [4, 5, 7, 8];
      return deletableStatus.includes(status);
    },
    
    // 判断是否可以取消订单
    canCancel(status) {
      // 待支付(1)可以取消订单
      return status == 1;
    },
    
    // 申请退款
    applyRefund(orderId) {
      uni.showModal({
        title: '提示',
        content: '确定要申请退款吗？',
        success: (res) => {
          if (res.confirm) {
            orderApi.refundOrder({
              id: orderId
            }).then(res => {
              if (res.code == 1) {
                uni.showToast({
                  title: '申请退款成功',
                  icon: 'success'
                });
                // 重新获取订单列表以更新状态
                this.getOrderList();
              } else {
                uni.showToast({
                  title: res.msg || '申请退款失败',
                  icon: 'none'
                });
              }
            }).catch(err => {
              console.error('申请退款失败:', err);
              uni.showToast({
                title: '网络错误，请重试',
                icon: 'none'
              });
            });
          }
        }
      });
    },
    
    // 删除订单
    deleteOrder(orderId) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该订单吗？',
        success: (res) => {
          if (res.confirm) {
            orderApi.deleteOrder({
              id: orderId
            }).then(res => {
              if (res.code == 1) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 重新获取订单列表以更新界面
                this.getOrderList();
              } else {
                uni.showToast({
                  title: res.msg || '删除失败',
                  icon: 'none'
                });
              }
            }).catch(err => {
              console.error('删除订单失败:', err);
              uni.showToast({
                title: '网络错误，请重试',
                icon: 'none'
              });
            });
          }
        }
      });
    },
    
    // 取消订单
    cancelOrder(orderId) {
      uni.showModal({
        title: '提示',
        content: '确定要取消该订单吗？',
        success: (res) => {
          if (res.confirm) {
            orderApi.cancelOrder({
              id: orderId
            }).then(res => {
              if (res.code == 1) {
                uni.showToast({
                  title: '取消订单成功',
                  icon: 'success'
                });
                // 重新获取订单列表以更新状态
                this.getOrderList();
              } else {
                uni.showToast({
                  title: res.msg || '取消订单失败',
                  icon: 'none'
                });
              }
            }).catch(err => {
              console.error('取消订单失败:', err);
              uni.showToast({
                title: '网络错误，请重试',
                icon: 'none'
              });
            });
          }
        }
      });
    },
    
    // 确认收货
    confirmReceipt(orderId) {
      uni.showModal({
        title: '提示',
        content: '确定已收到货物吗？',
        success: (res) => {
          if (res.confirm) {
            orderApi.confirmOrder({
              id: orderId
            }).then(res => {
              if (res.code == 1) {
                uni.showToast({
                  title: '确认收货成功',
                  icon: 'success'
                });
                // 重新获取订单列表以更新状态
                this.getOrderList();
              } else {
                uni.showToast({
                  title: res.msg || '确认收货失败',
                  icon: 'none'
                });
              }
            }).catch(err => {
              console.error('确认收货失败:', err);
              uni.showToast({
                title: '网络错误，请重试',
                icon: 'none'
              });
            });
          }
        }
      });
    },
    
    // 获取订单列表
    getOrderList() {
      this.loading = true;
      
      // 构造请求参数
      const requestData = {
        user_id: this.userId
      };
      
      // 如果不是"全部"标签，则添加status参数
      const currentTabStatus = this.tabs[this.activeTab]?.status;
      if (currentTabStatus !== null && currentTabStatus !== undefined) {
        requestData.status = currentTabStatus;
      }
      
      // 发起请求获取订单列表
      orderApi.getOrderList(requestData).then(res => {
        if (res && res.data && res.data.list) {
          this.orders = res.data.list;
        } else {
          this.orders = [];
        }
      }).catch(err => {
        console.error('获取订单列表失败:', err);
        this.orders = [];
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 切换标签页
    switchTab(index) {
      if (this.activeTab === index) return;
      
      this.activeTab = index;
      
      // 计算滚动位置，使当前选中的标签居中显示
      const query = uni.createSelectorQuery();
      query.select('.tab-container').boundingClientRect();
      query.select('.tab-scroll').boundingClientRect();
      query.exec((res) => {
        if (res[0] && res[1]) {
          const containerWidth = res[0].width;
          const scrollWidth = res[1].width;
          const itemWidth = containerWidth / this.tabs.length;
          const targetScrollLeft = itemWidth * index - scrollWidth / 2 + itemWidth / 2;
          this.scrollLeft = Math.max(0, targetScrollLeft);
        }
      });
      
      // 获取新的订单列表
      this.getOrderList();
    },
    
    // 再次购买
    buyAgain(goodsId) {
      uni.navigateTo({
        url: `/pages/product/product?id=${goodsId}`
      });
    },
    
    // 跳转到订单详情
    goToOrderDetail(order) {
      // 将订单信息通过参数传递给订单详情页面
      uni.navigateTo({
        url: `/pages/orderDetail/orderDetail?orderInfo=${encodeURIComponent(JSON.stringify(order))}`
      });
    },
    
    // 跳转到商品详情
    goToProduct(goodsId) {
      uni.navigateTo({
        url: `/pages/product/product?id=${goodsId}`
      });
    }

  }
};
</script>

<style scoped>
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 标签页样式 */
.tab-scroll {
  background-color: #fff;
  white-space: nowrap;
  position: sticky;
  top: 0;
  z-index: 99;
}

.tab-container {
  display: inline-block;
  min-width: 100%;
  display: flex;
}

.tab-item {
  flex: 1;
  padding: 30rpx 0;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #ff0000;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 6rpx;
  background-color: #ff0000;
  border-radius: 3rpx;
}

/* 订单列表样式 */
.orders-container {
  padding: 20rpx;
}

.loading, .empty {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}

.order-card {
  background-color: #fff;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.order-no {
  font-size: 26rpx;
  color: #666;
}

.order-status {
  font-size: 26rpx;
  color: #FF8000;
  font-weight: bold;
}

.order-body {
  display: flex;
  padding: 20rpx 30rpx;
}

.order-body image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.order-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-title {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  margin-right: 10rpx;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-spec {
  font-size: 24rpx;
  color: #999;
  flex: 1;
  margin-right: 10rpx;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.order-time {
  font-size: 24rpx;
  color: #999;
  flex: 1;
}

.price {
  font-size: 27rpx;
  white-space: nowrap;
}

.count {
  font-size: 26rpx;
  color: #666;
  white-space: nowrap;
}

.order-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f5f5f5;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

.order-actions {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.action-btn {
  padding: 0rpx 18rpx;
  font-size: 24rpx;
  border-radius: 25px;
  background-color: #fff;
  color: #666;
  margin-left: 10rpx;
}

.delete-btn {
  color: #ff0000;
  border-color: #ff0000;
}

.cancel-btn {
  color: #ff6600;
  border-color: #ff6600;
}

.confirm-btn {
  color: #00aa00;
  border-color: #00aa00;
}
</style>